package com.crm.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.crm.domain.role.SysRole;
import com.crm.crm.domain.SysUser;
import com.crm.crm.domain.dto.UserPageQueryParam;
import com.crm.crm.domain.dto.UserStatusDto;
import com.crm.crm.domain.vo.UserExcelVo;
import com.crm.crm.domain.vo.UserVo;
import com.crm.crm.domain.vo.business.result.HttpStatus;
import com.crm.crm.domain.vo.business.result.TableDataInfo;
import com.crm.crm.mapper.UserMapper;
import com.crm.crm.mapper.UserRoleMapper;
import com.crm.crm.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServicelmpl extends ServiceImpl<UserMapper, SysUser> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeptServicelmpl deptService;
    @Autowired
    private UserRoleMapper userRoleMapper;


    //根据部门ID查询员工表员工信息
    @Override
    public List<SysUser> getOwner(Integer deptId) {
        return deptService.getAllUsersInDeptAndSubDepts(deptId);
    }
    //分页查询员工信息
    @Override
    public TableDataInfo<UserVo> pageQuery(UserPageQueryParam userPageQueryParams) {
        Page<SysUser> page = new Page<>(userPageQueryParams.getPageNum(), userPageQueryParams.getPageSize());
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(userPageQueryParams.getUserName()), SysUser::getUserName, userPageQueryParams.getUserName())
                .like(StringUtils.isNotEmpty(userPageQueryParams.getPhonenumber()), SysUser::getPhonenumber, userPageQueryParams.getPhonenumber())
                .eq(StringUtils.isNotEmpty(userPageQueryParams.getStatus()), SysUser::getStatus, userPageQueryParams.getStatus());
        if (StringUtils.isNotEmpty(userPageQueryParams.getBeginTime())&&StringUtils.isNotEmpty(userPageQueryParams.getEndTime())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate beginTime = LocalDate.parse(userPageQueryParams.getBeginTime(),formatter);
            LocalDate endTime = LocalDate.parse(userPageQueryParams.getEndTime(),formatter);
            queryWrapper.between(SysUser::getCreateTime,beginTime, endTime);
        }
        Page<SysUser> result = userMapper.selectPage(page, queryWrapper);
        //List<UserVo> sysUserVo = new ArrayList<>();
        List<SysUser> sysUser = page.getRecords();
        List<UserVo> sysUserVos = sysUser.stream().map(sysUser1 -> {

            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(sysUser1, userVo);
            userVo.setRoles(new ArrayList<>());
            userVo.setDept(deptService.selectById(sysUser1.getDeptId()));
            return userVo;
        }).collect(Collectors.toList());

        //TODO:实现角色权限之后，再返回admin的类型

        TableDataInfo<UserVo> data = new TableDataInfo<>();
        data.setTotal(result.getTotal());
        data.setRows(sysUserVos);
        data.setCode(HttpStatus.SUCCESS);
        data.setMsg("查询成功");
        return data;
    }
    //获取所有角色
    @Override
    public List<SysRole> findAllRoles() {
        List<SysRole> sysRoles = userRoleMapper.selectAllRoles();
        return sysRoles;
    }

    //批量保存 角色ID
    @Override
    public void saveBatchRoleIds(Long userId, List<Long> roleIds) {
        if (roleIds != null && !roleIds.isEmpty()) {
            userMapper.saveBatchRoleIds(userId, roleIds); // 插入新的角色
        }
    }
//查询roleId
    @Override
    public List<Long> selectRoleIds(Integer id) {
        List<Long> list = userMapper.selectRoleIds(id);
        return list;
    }
//修改用户状态
    @Override
    public void changeStatus(UserStatusDto userStatusDto) {
        String status = userStatusDto.getStatus();
        Long userId = userStatusDto.getUserId();
        userMapper.changeStatus(status,userId);
    }
        //重置密码
    @Override
    public void resetPwd(String password, Long userId) {
        userMapper.resetPwd(password,userId);
    }
    //修改之前 先删除
    @Override
    public void deleteRoleIds(Long userId) {
        userMapper.deleteRoleIds(userId);
    }

    @Override
    public List<UserExcelVo> getExcelData(UserPageQueryParam userPageQueryParam) {
        Page<SysUser> page = new Page<>(userPageQueryParam.getPageNum(), userPageQueryParam.getPageSize());
        List<SysUser> sysUsers = page.getRecords();
        List<UserExcelVo> userExcelVos = sysUsers.stream().map(sysUser -> {
            UserExcelVo userExcelVo = new UserExcelVo();
            BeanUtils.copyProperties(sysUser, userExcelVo);
            Long userId = sysUser.getUserId();
            List<Long> roleIds = userMapper.selectRoleIds(userId.intValue());
            userExcelVo.setExcelRoleIds(roleIds.stream().map(roleId -> roleId.toString()).collect(Collectors.joining(",")));
            return userExcelVo;
        }).collect(Collectors.toList());
        return userExcelVos;
    }






    /**
     * 根据员工姓名查询员工信息
     * @param owner
     * @return
     */
    public  SysUser getUserById(String owner) {

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, owner);
        return userMapper.selectOne(wrapper);
    }

}
